/*
 * @Author: Yonyou
 * @Date: 2020-03-10 16:02:30
 * @LastEditTime: 2020-12-29 14:26:49
 * @LastEditors: hanfengmi
 * @Description: request请求封装
 */
/**
 * request 网络请求工具
 * 更详细的api文档: https://bigfish.alipay.com/doc/api#request
 */
import {
  extend
} from 'umi-request'
import router from 'umi/router'

import {
  // loginOut,
  getUrlKey
} from '@/utils/index'

/**
 * 异常处理程序
 */
const errorHandler = (ApiCode, msg) => {
  //todo show Error
  console.log(ApiCode, msg)
}

/**
 * 配置request请求时的默认参数
 */
const request = extend({
  mode: 'cors'
  // errorHandler, // 默认错误处理
  // credentials: 'include', // 默认请求是否带上cookie
})

request.interceptors.request.use(async (url, options) => {
  let fwq_token = localStorage.getItem('fwq-auth-token')
  let userInfo = localStorage.getItem('fwq-user-info')
  // 从url中获取加密ciId
  if (fwq_token) {
    const headers = {
      'Authorization': `bearer ${fwq_token}`,
      'user_id': JSON.parse(userInfo).encUserId,
      'c_id': getUrlKey('ciId')
    }
    return {
      url: url,
      options: {
        ...options,
        headers: headers
      }
    }
  } else {
    return {
      url: url,
      options: {
        ...options,
        headers: {
          'c_id': getUrlKey('ciId')
        }
      }
    }
  }
})

request.interceptors.response.use(async (response, request) => {
  if (response.status === 200) { //200
    const data = await response.clone().json()
    if (data.ErrorCode && data.ErrorCode !== '200') { // java使用
      //! noerror 错误不提示用户
      !request.headers.noerror && errorHandler(data.ApiCode, data.ErrorMsg)
      return response
    }
    if (!data.Success) { // 兼容php
      //! noerror 错误不提示用户
      !request.headers.noerror && errorHandler(data.Code, data.Message)
      return response
    }
    return response
  } else if (response.status === 401 || response.status === 403) {
    let userInfo = localStorage.getItem('fwq-user-info')
    localStorage.removeItem('fwq-auth-token')
    if (!userInfo) { // 未登录，直接登录
      // ! 跳转外部登录
      // loginOut('login')
      // !跳转内部登录
      router.push('/login')
      return false
    }
    // window.g_app._store.dispatch({
    //   type: 'user/GetTocken',
    //   payload: {
    //     user_id: JSON.parse(userInfo).userId,
    //     ciId: JSON.parse(userInfo).ciId
    //   }
    // })
  }
})

export default request
